<template>
    <view class="confirm-order">
        <view class="confirm-bg"></view>
        <view class="inner" v-if="goods.length>0">
            <view class="dizhi" @tap="toAddress">
                <image src="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/order/dingwei.png" mode="widthFix" class="dingwei-img"/>
                <view class="right">
                    <view class="right-left" v-if="add!='' && add!=null">
                        <view class="right-left-top">
                            <text>{{ add.consignee }}</text>
                            <text class="phone">{{ add.mobile }}</text>
                        </view>
                        <view class="right-left-bot">{{ add.province + add.city + add.district + add.address }}</view>
                    </view>
                    <view class="right-add" v-else>添加收货地址</view>
                    <image src="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/more-grey.png" mode="widthFix" class="more-img">
                </view>
            </view>
            <view class="confirm-order-goods shop-confirm-order-goods">
                <view class="confirm-order-goods-logo">
                    <image :src="store_info.wap_login_logo" mode="widthFix"/>
                    <text>{{ store_info.store_title }}</text>
                </view>
                <view class="order-goods-items">
                    <view class="order-goods-item" v-for="(item,index) in goods" :key="index">
                        <image :src="item.goods_img" class="goods-img"></image>
                        <view class="right">
                            <view class="goods-name">{{ item.goods_name }}</view>
                            <view class="goods-spec" v-if="item.item_name">已选：{{ item.item_name }}</view>
                            <view class="goods-bot">
                                <view class="goods-bot-left">
                                    <text>¥</text>
                                    <text class="large">{{ item.goods_price }}</text>
                                </view>
                                <view class="goods-bot-right">
                                    <text :class="{'dis':form.goods_num<=1}" @click="addAndSubtract(item,-1)">-</text>
                                    <text>{{ form.goods_num }}</text>
                                    <text :class="{'dis':form.goods_num>=item.store_count}"
                                          @click="addAndSubtract(item,1)">+
                                    </text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="rows">
                    <view class="row">
                        <view class="left">运费</view>
                        <view class="right">¥{{ ship_price }}</view>
                    </view>
                    <view class="row">
                        <view class="left">小计</view>
                        <view class="right">¥{{ total_amount }}</view>
                    </view>
                </view>
            </view>
            <view class="goods-row">
                <view class="goods-row-tit">备注</view>
                <u-input border="none" class="body_phone_input" placeholder="请填写备注信息(选填)"
                         placeholderClass="input-placeholder" type="text" fontSize="26rpx" clearable
                         v-model="form.user_note">
                </u-input>
                <view style="height: 20rpx;"></view>
            </view>
            <view class="goods-row" v-if="false">
                <view class="goods-row-tit">交易密码</view>
                <u-input border="none" class="body_phone_input" placeholder="请填写交易密码"
                         placeholderClass="input-placeholder" type="password" fontSize="26rpx" clearable
                         v-model="form.paypwd">
                </u-input>
                <view style="height: 20rpx;"></view>
            </view>
            <view class="goods-row">
                <view class="goods-row-tit">请选择支付方式</view>
                <view class="pay-items">
                    <view @tap="changePay(item.code)" class="pay-item" v-for="(item,index) in pay_list" :key="index">
                        <image mode="widthFix" :src="`https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/order/zf-${item.code}.png`" class="pay-item-left-img"/>
                        <text>{{ item.name }}</text>
                        <image mode="widthFix"
                               :src="form.pay_code==item.code?'https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/checkbox-sel.png':'https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/checkbox.png'"
                               class="pay-item-img"/>
                    </view>
                </view>
            </view>
            <view style="height: 120rpx;"></view>
        </view>
        <view class="confirm-order-bot" v-if="goods.length>0">
            <view class="left">
                <text>合计:</text>
                <text class="amount">{{ amount }}</text>
                <text>元</text>
            </view>
            <button type="default" class="zf-btn" @click="tijiao()" :disabled="btnDisabled">立即支付</button>
        </view>
        <u-popup :show="showPaypwd" mode="center" :customStyle="{'width':'80%'}" round="5" :closeOnClickOverlay="false"
                 :overlayOpacity="0.6">
            <view class="paypwd-container">
                <image src="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/close.png" mode="widthFix" class="close-img" @click="showPaypwd=false">
                </image>
                <view class="title">交易密码</view>
                <view class="form-rows">
                    <u-input border="none" class="row-input" placeholder="请填写交易密码" placeholderClass="input-placeholder"
                             type="password" fontSize="26rpx" clearable v-model="form.paypwd">
                    </u-input>
                </view>
                <view class="btn-container">
                    <button class="con-btn" @click="queding" :disabled="btnDisabled">确认</button>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import {
    payment
} from "../../common/helper";

var validate = require("@/components/validate/validate.js");
var _this;
export default {
    data() {
        return {
            form: {
                action: '',
                act: '',
                address_id: 0,
                goods_num: 1,
                goods_id: 0,
                pay_code: '',
                item_id: 0,
                pay_code: '',
                user_note: '',
                paypwd: '',
                order_id: 0
            },
            showPaypwd: false,
            btnDisabled: false,
            store_info: '',
            show: false,
            add: '',
            goods: '',
            pay_list: [],
            pay_code: '',
            xiaoji: '',
            ship_price: 0
        }
    },
    onLoad(e) {
        _this = this
        if (e.action) {
            _this.form.action = e.action
        }
        if (e.goods_id) {
            _this.form.goods_id = e.goods_id
        }
        if (e.goods_num) {
            _this.form.goods_num = e.goods_num
        }
        if (e.item_id) {
            _this.form.item_id = e.item_id
        }
        if (e.order_id) {
            _this.form.order_id = e.order_id
        }
        this.get_confirm()
        uni.$on('chooseAddress', res => {
            _this.form.address_id = res
            _this.getaddress()
        })

        this.officialConfig()
    },
    onUnload() {
        uni.$off('chooseAddress')
    },
    computed: {
        amount: {
            cache: false,
            get() {
                if (_this.goods == '') {
                    return 0.0
                }
                return _this.goods[0]['goods_price'] * _this.form.goods_num + _this.ship_price
            }
        },
        total_amount: {
            cache: false,
            get() {
                if (_this.goods == '') {
                    return 0.0
                }
                return _this.goods[0]['goods_price'] * _this.form.goods_num
            }
        },
        showMima: {
            cache: false,
            get() {
                let arr = ['money', 'mcbt']
                return arr.includes(_this.form.pay_code)
            }
        }
    },
    methods: {
        addAndSubtract(item, num) {
            if (num < 0) {
                if (_this.form.goods_num + num < 1) {
                    return
                }
                --_this.form.goods_num
            } else {
                if (_this.form.goods_num + num > item.store_count) {
                    return
                }
                ++_this.form.goods_num
            }
        },
        // 输入金额方法
        checkNum(e) {
            let val = e + ''.replace(/(^\s*)|(\s*$)/g, "")
            if (val <= 0) {
                this.$nextTick(() => {
                    this.use_jinbi = '';
                })
                return
            }
            if (!val) {
                this.$nextTick(() => {
                    this.use_jinbi = '';
                })
                return
            }
            if (val > this.user_jinbi) {
                this.$nextTick(() => {
                    this.use_jinbi = this.user_jinbi;
                })
                return
            }
            var reg = /[^\d.]/g
            // 只能是数字和小数点，不能是其他输入
            val = val.replace(reg, "")
            // // 保证第一位只能是数字，不能是点
            val = val.replace(/^\./g, "");
            // // 小数只能出现1位
            val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
            // // 小数点后面保留2位
            val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
            val = (val.match(/^\d*(\.?\d{0,2})/g)[0]) || ''
            // console.log(val);
            this.$nextTick(() => {
                this.use_jinbi = val;
            })
        },
        //跳转到地址列表
        toAddress() {
            this.$u.route({
                url: 'pages/center/address-list',
                params: {
                    is_cart: 1
                }
            })
        },
        //获取地址数据
        async getaddress() {
            const params = {
                address_id: this.form.address_id
            }
            const data = await _this.$post('api/Address', params)
            if (data.code == 200) {
                this.add = data.data.address
            } else {
                uni.$u.toast(data.msg)
                setTimeout(() => {
                    uni.navigateBack({})
                }, 2000)
            }
        },
        //切换支付方式
        changePay(code) {
            if (this.form.pay_code == code) {
                return;
            }
            this.form.pay_code = code
        },
        tijiao() {
            if (_this.showMima) {
                _this.showPaypwd = true
            } else {
                _this.form.act = 'yes'
                _this.get_confirm()
            }
        },
        queding() {
            let rule = [{
                name: 'paypwd',
                rules: ['require', 'min:6'],
                errorMsg: {
                    require: '请输入交易密码',
                    min: '交易密码最少6位'
                }
            }]
            let check = validate.check(this.form, rule);
            if (!check) {
                // 获取错误信息
                let err = validate.getError();
                uni.$u.toast(err[0])
                return
            }
            _this.form.act = 'yes'
            _this.get_confirm()
        },
        //获取订单生成初始数据
        async get_confirm() {
            if (_this.form.act == 'yes') {
                let openid = uni.getStorageSync('openid') || 'o4RE35WBIPcCtRZDphyMwBozNK80'
                _this.btnDisabled = true
                setTimeout(() => {
                    _this.btnDisabled = false
                }, 2000)
            }
            const data = await _this.$post('api/AddOrder', _this.form)
            console.info({
                data
            })
            if (data.code == 100) {
                uni.$u.toast(data.msg)
                setTimeout(() => {
                    uni.navigateBack({})
                }, 2000)
            } else if (data.code == -100) {
                uni.$u.toast(data.msg)
                setTimeout(() => {
                    uni.$u.route({
                        url: 'pages/center/paypwd',
                        type: 'redirectTo'
                    })
                }, 2000)
            } else if (data.code == 200) {
                uni.$u.toast(data.msg)
                setTimeout(() => {
                    uni.$u.route({
                        url: 'pages/order/order-list',
                        type: 'redirectTo',
                        params: {
                            status: 2
                        }
                    })
                }, 2000)
            } else if (data.code == 10) {
                this.add = data.data.add
                if (this.add) {
                    this.form.address_id = this.add.address_id
                    this.getaddress()
                }
                this.goods = data.data.goods
                this.pay_list = data.data.pay_list
                this.form.pay_code = this.pay_list[0]['code']
                this.ship_price = data.data.ship_price
                this.store_info = data.data.store_info
            } else if (data.code == 30) {
                //唤起微信支付
                uni.requestPayment({
                    provider: data.data.pay_code,
                    orderInfo: data.data.result,
                    success: (res) => {
                        this.nextStep(true)
                    },
                    fail(err) {
                        this.nextStep(false)
                    }
                });
            } else if (data.code === 50) {
                try {
                    await payment(data)

                    this.nextStep(true)
                } catch (e) {
                    this.nextStep(false)
                }
            } else {
                uni.$u.toast(data.msg)
            }
        },
        nextStep(isSuccess = true) {
            if (isSuccess) {
                uni.$u.toast('支付成功')
                setTimeout(() => {
                    uni.$u.route({
                        url: 'pages/order/order-list',
                        type: 'redirectTo',
                        params: {
                            status: 2
                        }
                    })
                }, 2000)
            } else {
                uni.$u.toast('支付失败')
                setTimeout(() => {
                    uni.$u.route({
                        url: 'pages/order/order-list',
                        type: 'redirectTo',
                        params: {
                            status: 1
                        }
                    })
                }, 2000)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
@import "@/static/css/order.scss";
</style>